package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * 雪花 ID 生成器
 */
@Slf4j
public class IdUtils {

    private static SnowflakeIdWorker snowflakeIdWorker;

    public static Long getId() {
        return initSnowflakeIdWorker().nextId();
    }

    private static SnowflakeIdWorker initSnowflakeIdWorker() {
        if (snowflakeIdWorker == null){
            synchronized (IdUtils.class) {
                if (snowflakeIdWorker == null ){
                    Long workerId = getWorkId();
                    Long dataCenterId = getDataCenterId();
                    log.info("[雪花ID初始化] workerId=>{} dataCenterId=>{}",workerId,dataCenterId);
                    snowflakeIdWorker = new SnowflakeIdWorker(workerId, dataCenterId);
                }
            }
        }
        return snowflakeIdWorker;
    }

    private static Long getWorkId() {
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for (int b : ints) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            log.info("[雪花ID初始化] 获取WorkId错误",e);
            return RandomUtils.nextLong(0, 31);
        }
    }
    private static Long getDataCenterId() {
        int[] ints = StringUtils.toCodePoints(SystemUtils.getHostName());
        int sums = 0;
        for (int i : ints) {
            sums += i;
        }
        return (long) (sums % 32);
    }
}
